package com.jmp.im;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

@Slf4j
public class ImClient {
    public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");

    private static final String URL_CREATE = "https://api.netease.im/nimserver/user/create.action";
    private static final String URL_UPDATE = "https://api.netease.im/nimserver/user/updateUinfo.action";

    private OkHttpClient client = new OkHttpClient();

    private String appKey;
    private String appSecret;

    public ImClient() {
        this("ca8aa56ec29ed73cb02cb144da272a8c", "32b682e6afe7");
    }

    public ImClient(String appKey, String appSecret) {
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    public CreateResponse create(CreateRequest request) {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("accid", request.getAccid());
        builder.add("name", request.getName());
        builder.add("icon", request.getIcon());
        builder.add("token", request.getToken());
        if (StringUtils.isNoneBlank(request.getMobile())) {
            builder.add("mobile", request.getMobile());
        }
        if (Objects.nonNull(request.getGender())) {
            builder.add("gender", String.valueOf(request.getGender()));
        }
        if (Objects.nonNull(request.getEx())) {
            builder.add("ex", JSON.toJSONString(request.getEx()));
        }
        return execute(URL_CREATE, builder, new TypeReference<ImResponse<CreateResponse>>() {
        });
    }

    public void update(UpdateRequest request) {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("accid", request.getAccid());
        if (StringUtils.isNoneBlank(request.getName())) {
            builder.add("name", request.getName());
        }
        if (StringUtils.isNoneBlank(request.getIcon())) {
            builder.add("icon", request.getIcon());
        }
        if (StringUtils.isNoneBlank(request.getMobile())) {
            builder.add("mobile", request.getMobile());
        }
        if (Objects.nonNull(request.getGender())) {
            builder.add("gender", String.valueOf(request.getGender()));
        }
        execute(URL_UPDATE, builder, null);
    }

    private <T> T execute(String url, FormBody.Builder builder, TypeReference<ImResponse<T>> typeReference) {
        String nonce = "1239faldf";
        String curTime = String.valueOf(System.currentTimeMillis() / 1000);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        Request request = new Request.Builder()
                .url(url)
                .header("AppKey", appKey)
                .header("Nonce", nonce)
                .header("CurTime", curTime)
                .header("CheckSum", checkSum)
                .post(builder.build())
                .build();
        String result = null;
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
            log.debug("response:{}", result);
            if (Objects.nonNull(typeReference)) {
                ImResponse<T> imResponse = JSON.parseObject(result, typeReference);
                if (imResponse.getCode() != 200) {
                    log.error("url:{},response:{}", url, result);
                    return null;
                }
                return imResponse.getInfo();
            } else {
                ImResponse imResponse = JSON.parseObject(result, ImResponse.class);
                if (imResponse.getCode() != 200) {
                    log.error("url:{},response:{}", url, result);
                    return null;
                }
            }
        } catch (Exception e) {
            log.debug("response:{}", result);
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
